import re
from django_redis import get_redis_connection
from rest_framework.serializers import ModelSerializer
from rest_framework_jwt.settings import api_settings

from apps.users.models import User
from rest_framework import serializers

from apps.users.utils import set_token


class RegisterModelSerializer(ModelSerializer):
    """注册"""
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, write_only=True)
    token = serializers.CharField(label='token', read_only=True)

    class Meta:
        model = User
        fields = ['sms_code','username','id','password','token','avatar','mobile']

        # 校验
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 6,
                'max_length': 16,
                'error_messages': {
                    'min_length': '仅允许6-16个字符的密码',
                    'max_length': '仅允许6-16个字符的密码',
            },
            }
        }

        def validate(self, attrs):
            """短信验证码"""
            code = attrs['sms_code']
            # 获取redis中的验证码
            redis_conn = get_redis_connection('code')
            # 获取手机号码
            mobile = attrs['mobile']
            redis_code = redis_conn.get(mobile)
            if redis_code is None:
                raise serializers.ValidationError('验证码过期')
            # 注意 redis的数据是 bytes类型
            if redis_code.decode() != code:
                raise serializers.ValidationError('验证码不正确')

            return attrs

        def validate_mobile(self, value):
            """手机号验证"""
            if not re.match(r'1[345789]\d{9}', value):
                raise serializers.ValidationError('手机号格式不正确')

            return value

    def create(self, validated_data):
        """保存数据"""
        del validated_data['sms_code']

        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        # 生成token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token

        return user
